import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression

df=pd.read_csv('train_titanic.csv')
print(df.info())
print(df.describe())

#对fare填充,用平均值
df.loc[df['Fare'].isnull(),'Fare']=32.180730
#对港口填充，用众数

df.loc[df['Embarked'].isnull(),'Embarked']='S'
#删除船舱信息，缺失值太多cabin
del df['Cabin']
train_x=df.loc[df['Age'].notnull(),['Survived','Sex','Pclass','Fare']]
test_x=df.loc[df['Age'].isnull(),['Survived','Sex','Pclass','Fare']]

from sklearn.preprocessing import OneHotEncoder,StandardScaler
onehot=OneHotEncoder()
x_onehot_train=onehot.fit_transform(train_x[['Survived','Sex','Pclass']]).toarray()
x_onehot_test=onehot.fit_transform(test_x[['Survived','Sex','Pclass']]).toarray()

std=StandardScaler()
x_std_train=std.fit_transform(train_x[['Fare']])
x_std_test=std.fit_transform(test_x[['Fare']])

import numpy as np
train_x=np.c_[x_onehot_train,x_std_train]
test_x=np.c_[x_onehot_test,x_std_test]

train_y= df.loc[df['Age'].notnull(),'Age']

model=LinearRegression()
model.fit(train_x,train_y)
y_=model.predict(test_x)

df.loc[df['Age'].isnull(),'Age']=y_
print(df.info())